import math
import datetime
import csv
from zzz import *
import subprocess
import tqdm
from ebooklib import epub
help = '''
python epub.py <input_dir|input_filelist> <output_epub> <title> <chapter_title_from_first_line:True>
将一堆txt文件转换为epub
chapter_title_from_first_line:是否取第一行作为标题，如果否，取文件名
'''
txt2html = 'txt2html/txt2html.exe'
prepend = [['', '信息'], ["temp/000.html", "凡例"],
           ['temp/terms.html', '术语']]


def export_term_rtf():
    terms = [['中文名', '原文', '注释']]
    with open("terms.csv", 'r', encoding='utf-8-sig') as f:
        reader = list(csv.DictReader(f))
        for row in reader:
            terms.append([row['cn'], row['jp'] or row['hira']
                         or row['en'] or "/", row['info']])
    doc = '''
<html><head>
<title>术语</title>
</head>
<body>
{}
</body>
</html>
'''
    content = []
    for i in terms:
        content.append(f"<div><span>{i[0]}</span>[{i[1]}]：{i[2]}。<br/></div>")
    with open("temp/terms.html", "w", encoding='utf-8') as f:
        f.write(doc.format("\n".join(content)))


def convert_txt_to_html(input_file, output_file=None, title=None, css_file=None, bold=False, italic=False, urls=False, entities=False, fix_paragraphs=None):
    # 构建命令行参数
    command = [txt2html, input_file]

    if output_file:
        command.extend(['-o:"{}"'.format(output_file)])

    if title:
        command.extend(['-t:"{}"'.format(title)])

    if css_file:
        command.extend(['-css:"{}"'.format(css_file)])

    if bold:
        command.append('-bold')

    if italic:
        command.append('-italic')

    if urls:
        command.append('-urls')

    if entities:
        command.append('-entities')

    if fix_paragraphs:
        command.extend(['-fixparagraphs:{}'.format(fix_paragraphs)])

    # 调用外部程序
    subprocess.run(command)


def get_modified_time(filepath):
    stat = os.stat(filepath)
    modified_time = stat.st_mtime
    return modified_time


def is_modified(src, dst):
    return get_modified_time(src) >= get_modified_time(dst)


def set_time():
    today = datetime.date.today()
    datestr = today.strftime("%Y-%m-%d")
    html = "0.html"
    data = file.readstr(html)
    data = data.replace("{time}", datestr)
    return bytes(data, encoding='utf-8')


def create_epub(title, output, flist, use_first_line):
    export_term_rtf()
    sp = ["nav"]
    index_export = []
    html1 = set_time()
    convert_txt_to_html(input_file="000.rtf",
                        output_file="temp/000.html")
    # 创建 EPUB 书籍对象
    book = epub.EpubBook()

    # 添加元数据
    book.set_identifier(title)
    book.set_title(title)
    book.set_language('zh')
    book.add_author('zzzzzzzs')

    # 添加封面
    # cover_image = epub.EpubItem(file_name='cover.jpg', media_type='image/jpeg', content=open('path/to/cover.jpg', 'rb').read())
    # book.add_item(cover_image)

    for (i, t) in prepend:
        content = file.readstr(i) if i else html1
        fname = os.path.basename(i or "0.html").replace('.html', '.xhtml')
        chapter = epub.EpubHtml(
            title=t, file_name=fname, content=content)
        book.add_item(chapter)
        print("add", t, fname)
        sp.append(chapter)
        index_export.append(t)
    # 添加文件
    for index, file_path in tqdm.tqdm(enumerate(flist)):
        if use_first_line:
            f = file.openstr(file_path)
            title = f.readline().strip()
            f.close()
        else:
            title = os.path.splitext(os.path.basename(file_path))[0]

        # 转换出一个html
        html_output_file = os.path.join("./temp", file_path+'.html')
        if not file.exist(html_output_file) or is_modified(file_path, html_output_file):
            convert_txt_to_html(input_file=file_path,
                                output_file=html_output_file)
        # 读取文件内容
        content = file.read(html_output_file)
        # 创建章节
        fname = f'{title}.xhtml'
        chapter = epub.EpubHtml(
            title=title, file_name=fname, content=content)
        book.add_item(chapter)
        print("add", title, fname)
        sp.append(chapter)
        index_export.append(title)

        # 将章节添加到阅读顺序中
        # book.add_item(epub.EpubNav())

    # 设置阅读顺序
    book.toc = [epub.Link(item.file_name, item.title, item.file_name)
                for idx, item in enumerate(book.items)]
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())
    book.spine = sp

    # 生成 EPUB 文件
    epub.write_epub(output, book, {})
    file.write("index.rtf", "\n".join(index_export))
    # shutil.rmtree("./temp", ignore_errors=True)


def get_title(flist):
    ttl = "叹息的亡灵想要隐退"
    maxx = 0
    for i in flist:
        try:
            num = int(reg.search(i, "[0-9]+")[0])
            if num and num < 900:
                maxx = max(num, maxx)
        except:
            pass
    ttl2 = f"{ttl}.web.1-{maxx}.epub"
    return ttl, ttl2


def sort_fn(x):
    num = reg.search(x, "[0-9]+[.]?[0-9]*")
    if not num:
        return -1
    num = num[0]
    f_num = float(num)
    if num.endswith(".0") and f_num:
        # volume
        f_num = f_num-0.001
    if f_num:
        return f_num
    return -1


block_txt = ['prompt.txt']
if __name__ == "__main__":
    flist = []
    a0 = "./"
    if os.path.exists(a0) and os.path.isfile(a0):
        flist = file.readstr(a0).splitlines()
    else:
        flist = [i for i in os.listdir(
            a0) if os.path.isfile(i) and i.endswith('txt') and i not in block_txt]
        flist.sort(key=sort_fn)

    title, output = get_title(flist)
    chapter_use_line = True
    # 创建 EPUB 文件
    create_epub(title, output, flist, chapter_use_line)
